# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from threading import Timer, enumerate
from time import sleep

import py_global
import logging

logger = logging.getLogger(__name__)


def func_name(arg0, arg1, *args, **kwargs):
    logging.info("args:%s,%s", arg0, arg1)


def loop_func(arg0, arg1, *args, **kwargs):
    func_name(arg0, arg1, *args, **kwargs)
    # 由于Timer只能执行一次，要循环触发可以使用递归调用
    global timer
    timer = Timer(interval=5, function=loop_func, args=('key', 'value', 10))
    timer.start()
    logger.info('thread length:%d', len(enumerate()))
    pass


def test_timer():
    # 设置间隔（单位秒）：多少秒钟后执行一次
    timer = Timer(interval=5, function=loop_func, args=('key', 'value', 10))
    timer.start()
    logging.debug("start")


class Clock(Timer):
    """
    Timer只执行一次，Clock可执行多次
    """

    def __init__(self, interval, function, *args, **kwargs):
        super().__init__(interval, function, *args, **kwargs)
        self.init_time = datetime.now()  # 初始时间
        self.alive_delta = timedelta(seconds=60)  # 存活时间

    def run(self):
        stop_time = self.init_time + self.alive_delta  # 停止时间
        while not self.finished.is_set():
            # 不能超过停止时间
            if datetime.now() > stop_time:
                # 执行完这次循环后终止循环
                self.finished.set()
            self.finished.wait(self.interval)
            self.function(*self.args, **self.kwargs)


def test_clock():
    clock = Clock(interval=5, function=func_name, args=('key', 'value', 10))
    clock.start()
    logger.info("start")
    # sleep(60)
    # clock.cancel()


if __name__ == '__main__':
    # test_timer()
    test_clock()

    pass
